<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label="菜单名称">
          <el-input v-model="listQuery.title" clearable class="filter-item" placeholder="菜单名称"/>
        </el-form-item>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList">查找</el-button>
        <el-button
          class="filter-item"
          style="float:right"
          type="info"
          icon="el-icon-sort"
          size="small"
          @click="toggleExpandAll">展开/折叠</el-button>
        <el-button
          v-hasPermi="['admin:sys:menu:create']"
          class="filter-item"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="startAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-if="refreshTable"
      :data="list"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :default-expand-all="isExpandAll"
      row-key="id"
      border>
      <el-table-column align="left" prop="title" label="菜单名称"/>
      <el-table-column align="center" prop="sequence" label="排序"/>
      <el-table-column align="center" prop="perms" label="权限标识"/>
      <el-table-column align="center" prop="component" label="组件路径"/>
      <el-table-column align="center" prop="createTime" label="创建时间"/>
      <el-table-column align="center" label="操作">
        <template slot-scope="{row}">
          <el-button
            v-hasPermi="['admin:sys:menu:update']"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(row)">修改</el-button>
          <el-button
            v-if="row.type !== 3"
            v-hasPermi="['admin:sys:menu:create']"
            size="small"
            type="text"
            icon="el-icon-plus"
            @click="handleAddSubMenu(row)">新增</el-button>
          <el-button
            v-hasPermi="['admin:sys:menu:delete']"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteMenu(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :close-on-click-modal="false" :title="dialogType == 1?'新增菜单':'修改菜单'" :visible.sync="dialogFormVisible" width="45%">
      <el-form ref="dialogForm" :rules="formRules" :model="dialogForm" label-width="120px">
        <el-form-item label="上级菜单" prop="pid">
          <el-cascader
            v-model="dialogForm.pid"
            :options="menuOptions"
            :show-all-levels="false"
            :emit-path="false"
            :props="{ checkStrictly: true,label:'title',value:'id',emitPath:false }"

            style="width: 100%;"/>
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="dialogForm.type" @change="handleTypeChange">
            <el-radio :label="1">目录</el-radio>
            <el-radio :label="2">菜单</el-radio>
            <el-radio :label="3">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="title">
              <el-input v-model="dialogForm.title" clearable placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sequence">
              <el-input-number v-model="dialogForm.sequence" :min="0" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col v-if="dialogForm.type!==1" :span="12">
            <el-form-item label="权限标识" prop="perms">
              <div class="flex_hcneter">
                <!-- :disabled="dialogForm.type == 2" -->
                <el-input

                v-model="dialogForm.perms" clearable placeholder=""/>
                <!-- <el-button
                @click="generate"
                v-if="dialogForm.type == 2" type="primary">权限生成</el-button> -->
              </div>
            </el-form-item>
          </el-col>
          <el-col v-if="dialogForm.type===2" :span="12">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="dialogForm.component" clearable placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col v-if="dialogForm.type!==3" :span="12">
            <el-form-item label="路由地址" prop="path">
              <el-input v-model="dialogForm.path" clearable placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col v-if="dialogForm.type!==3" :span="12">
            <el-form-item label="显示状态" prop="hidden">
              <el-radio-group v-model="dialogForm.hidden">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmEdit('dialogForm')">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { menuList, createMenu, menuDetail, updateMenu, delMenu } from '@/api/permission'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { rolelistRoleMenu } from '@/api/permission/role'
export default {
  name: 'menus',
  components: { Pagination },
  data() {
    return {
      list: [],
      listLoading: true,
      listQuery: {

      },
      downloadLoading: false,
      dialogFormVisible: false,
      dialogForm: { pid: 0 },
      dialogType: 1,
      formRules: {
        // pid: [{ required: true, message: '请选择上级菜单', trigger: 'blur' }],
        type: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
        title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
        sequence: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
        perms: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
        component: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
        hidden: [{ required: true, message: '请选择是否显示', trigger: 'blur' }],
        path: [{ required: true, message: '请输入路由地址', trigger: 'blur' }],
      },
      menuOptions: [],
      isExpandAll: false,
      refreshTable: true
    }
  },
  created() {
    this.getList()
    this.getMenuList({})
  },
  methods: {
    generate(){//生成权限
      let dialogForm = {...this.dialogForm}
      dialogForm.perms = 'frontend:' + this.randomRange(10)
      this.dialogForm = {...dialogForm}
    },
    /** 随机生成固定位数或者一定范围内的字符串数字组合
     * @param {Number} min 范围最小值
     * @param {Number} max 范围最大值，当不传递时表示生成指定位数的组合
     * @returns {String} 返回字符串结果
     * */
    randomRange(min, max){//生成随机权限
     var returnStr = "",
      range = (max ? Math.round(Math.random() * (max-min)) + min : min),
      arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
     for(var i=0; i<range; i++){
      var index = Math.round(Math.random() * (arr.length-1));
      returnStr += arr[index];
     }
     return returnStr;
    },
    async getMenuList() { // 菜单数据
      const response = await rolelistRoleMenu()
      const data1 = response.data || []
      this.menuOptions = data1
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    getList() {
      this.listLoading = true
      menuList(this.listQuery).then(response => {
        this.list = response.data || []
        this.listLoading = false
      })
    },
    handleTypeChange(val) {
      // 目录的上级菜单是目录类型
      // 菜单的上级菜单是目录和菜单类型
      // 按钮的上级菜单是目录、菜单和按钮类型
      let dialogForm = {...this.dialogForm}
      if(dialogForm.type == 1){
        delete dialogForm.perms
        delete dialogForm.component
      }else if(dialogForm.type == 3){
        delete dialogForm.component
        delete dialogForm.hidden
        delete dialogForm.path
      }
      this.dialogForm = {...dialogForm }
      // let types = []
      // if (val === 1) {
      //   types = [1]
      // }
      // if (val === 2) {
      //   types = [1, 2]
      // }
      // if (val === 3) {
      //   types = [1, 2, 3]
      // }
      // this.getMenuList({ types })
    },
    getFormMenuList(query) {
      menuList(query).then(response => {
        this.menuOptions = response.data || []
        this.dialogForm.pid = 0
      })
    },
    handleDeleteMenu(row) {
      this.$confirm(`您确定删除菜单："${row.title}"吗`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delMenu({ id: row.id }).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
          this.getMenuList({})
        })
      })
    },
    startAdd() {
      this.dialogForm = {
        pid: 0,
        type:1,
      }
      this.dialogFormVisible = true
      this.dialogType = 1
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
    },

    confirmEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogType === 1) {
            createMenu(this.dialogForm).then(response => {
              this.$message({
                message: '添加成功!',
                type: 'success'
              })
              this.getList()
              this.getMenuList({})
              this.dialogFormVisible = false
              this.dialogForm = {
                pid: 0
              }
            })
          } else {
            updateMenu(this.dialogForm).then(response => {
              this.$message({
                message: '修改成功!',
                type: 'success'
              })
              this.getList()
              this.getMenuList({})
              this.dialogFormVisible = false
              this.dialogForm = {
                pid: 0
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleEdit(row) {
      this.dialogType = 2
      menuDetail({ id: row.id }).then(res => {
        this.dialogForm = res.data || {}
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs.dialogForm.clearValidate()
        })
      })
    },
    handleAddSubMenu(row) {
      this.dialogForm = {}
      this.dialogType = 1
      this.dialogForm.pid = row.id
      let type = 1
      if(row.type == 1) type = 2
      if(row.type == 2) type = 3
      this.dialogForm.type = type
      this.dialogFormVisible = true
    }

  }

}
</script>
